from gui.wechat_gui import WechatGui
from myutils.window_helper import *
from model.exception import (
    ParkTokenFatalError,
    ParkTokenTokenParseError,
    ParkTokenWechatHwndError,
)
from model.token import Token, TokenType
import re
import json
from datetime import datetime
import myutils.services_helper as services_helper


class YimaGui(WechatGui):
    def __init__(self):
        super().__init__()
        self.fiddler_hwnd = None

    def set_fiddler_hwnd(self, hwnd):
        self.fiddler_hwnd = hwnd

    def check_env(self):
        super().check_env()
        if not self.fiddler_hwnd:
            raise ParkTokenFatalError("未找到fiddler窗口")

    def extract_token(self, fiddle_text) -> Token:
        """使用正则提取token与openid"""

        r_token = re.search(r'"token":"(.*?)"', fiddle_text)
        r_openid = re.search(r'"openId":"(.*?)"', fiddle_text)

        if r_token and r_openid:
            token = Token()
            token.userid = r_openid.group(1)
            token.data = json.dumps(
                {
                    "token": r_token.group(1),
                    "openId": r_openid.group(1),
                    "updateTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
                ensure_ascii=False,
            )
            token.type = TokenType.Yima
            return token
        else:
            raise ParkTokenTokenParseError(fiddle_text)

    def start(self):
        self.check_env()

        close_window(find_window_hwnd_first("一码YiMa"))
        try:
            max_window(self.hwnd)
        except Exception as e:
            raise ParkTokenWechatHwndError("微信窗口已关闭")
        self.click_image("./images/yima/wechat_mini_program.png")
        self.click_image("./images/yima/yima.png")
        max_window(self.fiddler_hwnd)
        self.click_image("./images/yima/fiddler_row.png")
        time.sleep(1)  # 等待请求完成
        self.hotkey("ctrl", "shift", "s")
        self.hotkey("ctrl", "x")
        services_helper.save_token(self.extract_token(get_clipboard_text()))
        close_window(find_window_hwnd_first("一码YiMa"))
